package com.neu.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.Serializable;
import java.net.InetSocketAddress;

/**
 * @author 杜佳辉
 * @version 1.0
 * @date 2024-12-03-20:45
 */
public class Client implements Serializable {
    private final String host;
    private int port;

    public Client(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        //定义干活的线程池 io线程池
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .remoteAddress(new InetSocketAddress(host, port))
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new HandlerClientHello());
                        }
                    });
            //连接远程节点，等待 sync
            ChannelFuture channelFuture = bootstrap.connect().sync();

            //发送消息到服务端 编码为utf-8
            channelFuture.channel().writeAndFlush(Unpooled.wrappedBuffer("hello world".getBytes()));
            //阻塞
            channelFuture.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        new Client("127.0.0.1", 8080).start();
    }
}
